<template>
  <div class="home-container">
    <!-- 轮播图 -->
    <div class="banner-section">
      <el-carousel height="400px" :interval="5000" type="card" indicator-position="outside">
        <el-carousel-item v-for="(item, index) in bannerList" :key="index">
          <div class="banner-item" :style="{backgroundImage: `url(${getImageUrl(item)})`}">
            <el-button type="primary" size="large" class="view-btn" @click="navigateToProduct(item)">
              立即查看 <el-icon class="el-icon--right"><ArrowRight /></el-icon>
            </el-button>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 特色服务 -->
    <div class="features-section">
      <div class="feature-item">
        <el-icon :size="40" color="#409EFF"><Discount /></el-icon>
        <h3>优惠多多</h3>
        <p>享受各种优惠活动</p>
      </div>
      <div class="feature-item">
        <el-icon :size="40" color="#409EFF"><TakeawayBox /></el-icon>
        <h3>品质保障</h3>
        <p>精选各类优质商品</p>
      </div>
      <div class="feature-item">
        <el-icon :size="40" color="#409EFF"><Van /></el-icon>
        <h3>极速配送</h3>
        <p>快速送达，准时必达</p>
      </div>
      <div class="feature-item">
        <el-icon :size="40" color="#409EFF"><Service /></el-icon>
        <h3>贴心服务</h3>
        <p>7×24小时客户服务</p>
      </div>
    </div>

    <!-- 推荐商品 -->
    <div class="section recommend-section">
      <div class="section-header">
        <h2 class="section-title">
          <span class="title-icon"></span>
          推荐商品
        </h2>
        <router-link to="/userWeb/category/1" class="more-link">
          查看更多 <el-icon><ArrowRight /></el-icon>
        </router-link>
      </div>
      <div class="product-list" v-loading="recommendLoading">
        <div v-for="product in recommendProducts" :key="product.id" class="product-item">
          <div class="product-card" @click="goToProductDetail(product.id)">
            <div class="product-img">
              <img :src="getImageUrl(product)" :alt="product.title">
            </div>
            <div class="product-info">
              <h3 class="product-title">{{ product.title }}</h3>
              <div class="product-price">
                <span class="current-price" v-if="product.specPrice">¥{{ product.specPrice }}</span>
                <span class="price-tips" v-else>查看规格价格</span>
                <span class="original-price" v-if="product.originPrice">¥{{ product.originPrice }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 热销商品 -->
    <div class="section hot-section">
      <div class="section-header">
        <h2 class="section-title">
          <span class="title-icon"></span>
          热销商品
        </h2>
        <router-link to="/userWeb/category/2" class="more-link">
          查看更多 <el-icon><ArrowRight /></el-icon>
        </router-link>
      </div>
      <div class="product-list" v-loading="hotLoading">
        <div v-for="product in hotProducts" :key="product.id" class="product-item">
          <div class="product-card" @click="goToProductDetail(product.id)">
            <div class="product-img">
              <img :src="getImageUrl(product)" :alt="product.title">
              <div class="sale-tag" v-if="product.sales > 100">热销</div>
            </div>
            <div class="product-info">
              <h3 class="product-title">{{ product.title }}</h3>
              <div class="product-price">
                <span class="current-price" v-if="product.specPrice">¥{{ product.specPrice }}</span>
                <span class="price-tips" v-else>查看规格价格</span>
                <span class="original-price" v-if="product.originPrice">¥{{ product.originPrice }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserWebIndex'
}
</script>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
// import { Discount, TakeawayBox, Van, Service, ArrowRight } from '@element-plus/icons-vue';
import axios from 'axios';

const router = useRouter();
const bannerList = ref([]);
const recommendProducts = ref([]);
const hotProducts = ref([]);
const recommendLoading = ref(false);
const hotLoading = ref(false);
const baseUrl = 'http://localhost:9191'; // 后端服务器基础URL

// 获取轮播图数据
const fetchBannerList = async () => {
  try {
    // 从API获取轮播图数据
    const response = await axios.get(`${baseUrl}/api/carousel`);
    if (response.data && response.data.code === '200') {
      bannerList.value = response.data.data || [];
    } else {
      // 如果获取失败，使用默认数据
      useDefaultBanners();
    }
  } catch (error) {
    console.error('获取轮播图数据失败:', error);
    // 如果出错，使用默认数据
    useDefaultBanners();
  }
};

// 使用默认轮播图数据
const useDefaultBanners = () => {
  bannerList.value = [
    {
      picture: 'https://img.alicdn.com/imgextra/i1/O1CN01yfhE4i1MKYnYLO4NG_!!6000000001418-0-tps-1920-450.jpg',
      title: '新品上市',
      description: '全场新品，限时折扣',
      goodId: 1
    },
    {
      picture: 'https://img.alicdn.com/imgextra/i3/O1CN01NRzS9v23gZBWNRHZM_!!6000000007293-0-tps-1920-500.jpg',
      title: '热卖商品',
      description: '畅销产品，口碑之选',
      goodId: 2
    },
    {
      picture: 'https://img.alicdn.com/imgextra/i2/O1CN01EmX5a523gZ8WWFNtA_!!6000000007290-0-tps-1920-500.jpg',
      title: '限时特惠',
      description: '折扣优惠，限时抢购',
      goodId: 3
    }
  ];
};

// 导航到商品详情页
const navigateToProduct = (item) => {
  if (item.goodId) {
    router.push(`/userWeb/product/${item.goodId}`);
  } else if (item.link) {
    navigateToCategory(item.link);
  }
};

// 获取推荐商品
const fetchRecommendProducts = async () => {
  recommendLoading.value = true;
  try {
    // 实际项目中从API获取
    const response = await axios.get(`${baseUrl}/api/good`);
    if (response.data && response.data.code === '200') {
      // 处理商品数据，确保字段名一致
      recommendProducts.value = (response.data.data || []).map(item => ({
        id: item.id,
        title: item.name || item.title || '未命名商品',
        cover: item.imgs || item.cover || item.img || item.picture,
        specPrice: item.specPrice, // 使用后端返回的规格价格
        originPrice: item.originPrice || item.originalPrice,
      }));
    } else {
      // 模拟数据
      recommendProducts.value = generateMockProducts(4);
    }
  } catch (error) {
    console.error('获取推荐商品失败:', error);
    // 模拟数据
    recommendProducts.value = generateMockProducts(4);
  } finally {
    recommendLoading.value = false;
  }
};

// 获取热销商品
const fetchHotProducts = async () => {
  hotLoading.value = true;
  try {
    // 实际项目中从API获取
    const response = await axios.get(`${baseUrl}/api/good/rank`, {
      params: { num: 8 }
    });
    if (response.data && response.data.code === '200') {
      // 处理商品数据，确保字段名一致
      hotProducts.value = (response.data.data || []).map(item => ({
        id: item.id,
        title: item.name || item.title || '未命名商品',
        cover: item.imgs || item.cover || item.img || item.picture,
        specPrice: item.specPrice, // 使用后端返回的规格价格
        originPrice: item.originPrice || item.originalPrice,
        sales: item.sales || item.sale || 0,
      }));
    } else {
      // 模拟数据
      hotProducts.value = generateMockProducts(8, true);
    }
  } catch (error) {
    console.error('获取热销商品失败:', error);
    // 模拟数据
    hotProducts.value = generateMockProducts(8, true);
  } finally {
    hotLoading.value = false;
  }
};

// 拼接图片URL
const getImageUrl = (item) => { 
  // 检查图片路径
  let imgPath = item.img || item.picture || item.imgUrl || item.cover || item.imgs;
  
  // 如果路径以http或https开头，说明是完整的URL，直接返回
  if (imgPath && (imgPath.startsWith('http://') || imgPath.startsWith('https://'))) {
    return imgPath;
  }
  
  // 如果路径以/file/开头，需要拼接后端服务器地址
  if (imgPath && imgPath.startsWith('/file/')) {
    return `${baseUrl}${imgPath}`;
  }
  
  // 其他情况直接拼接
  if (imgPath) {
    return `${baseUrl}/file/${imgPath}`;
  }

  // 默认图片
  return '';
};

// 生成模拟商品数据
const generateMockProducts = (count, isHot = false) => {
  const products = [];
  const categories = ['手机', '电脑', '耳机', '相机', '手表', '平板', '电视'];
  const brands = ['Apple', 'Samsung', 'Huawei', 'Xiaomi', 'Sony', 'Dell', 'HP'];
  
  for (let i = 1; i <= count; i++) {
    const price = Math.floor(Math.random() * 9000) + 1000;
    const category = categories[Math.floor(Math.random() * categories.length)];
    const brand = brands[Math.floor(Math.random() * brands.length)];
    
    products.push({
      id: i,
      title: `${brand} ${category} ${isHot ? '热门款' : '新款'} ${i}`,
      cover: `https://picsum.photos/id/${i+30}/300/300`,
      specPrice: price, // 模拟的规格价格
      originPrice: Math.floor(price * 1.2),
      sales: isHot ? Math.floor(Math.random() * 500) + 100 : Math.floor(Math.random() * 100)
    });
  }
  
  return products;
};

// 跳转到商品详情
const goToProductDetail = (id) => {
  router.push(`/userWeb/product/${id}`);
};

// 跳转到分类
const navigateToCategory = (categoryId) => {
  router.push(`/userWeb/category/${categoryId}`);
};

onMounted(() => {
  fetchBannerList();
  fetchRecommendProducts();
  fetchHotProducts();
});
</script>

<style scoped>
.home-container {
  padding-bottom: 30px;
}

/* 轮播图样式 */
.banner-section {
  margin-bottom: 30px;
}

.banner-item {
  height: 100%;
  background-size: cover;
  background-position: center;
  border-radius: 4px;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
}

.banner-content {
  padding: 30px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  max-width: 50%;
  border-radius: 4px;
  margin-left: 50px;
}

.banner-content h2 {
  font-size: 28px;
  margin-bottom: 15px;
}

.banner-content p {
  font-size: 16px;
  margin-bottom: 20px;
}

.view-btn {
  position: absolute;
  bottom: 30px;
  right: 30px;
  padding: 12px 25px;
  font-weight: bold;
  border-radius: 30px;
  border: 2px solid #fff;
  background: linear-gradient(to right, #409EFF, #007bff);
  box-shadow: 0 4px 15px rgba(0, 123, 255, 0.4);
  transition: transform 0.3s, box-shadow 0.3s;
}

.view-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(0, 123, 255, 0.6);
  background: linear-gradient(to right, #007bff, #0056b3);
}

.view-btn .el-icon--right {
  margin-left: 5px;
  transition: transform 0.3s;
}

.view-btn:hover .el-icon--right {
  transform: translateX(3px);
}

/* 特色服务 */
.features-section {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  margin-bottom: 40px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.feature-item {
  flex: 1;
  min-width: 200px;
  text-align: center;
  padding: 20px;
}

.feature-item h3 {
  margin: 15px 0 10px;
  font-size: 18px;
}

.feature-item p {
  color: #666;
  font-size: 14px;
}

/* 商品区域共用样式 */
.section {
  margin-bottom: 40px;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 22px;
  margin: 0;
  display: flex;
  align-items: center;
}

.title-icon {
  display: inline-block;
  width: 4px;
  height: 20px;
  background-color: #409EFF;
  margin-right: 10px;
  border-radius: 2px;
}

.more-link {
  color: #409EFF;
  text-decoration: none;
  display: flex;
  align-items: center;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
}

.product-item {
  transition: transform 0.3s;
}

.product-item:hover {
  transform: translateY(-5px);
}

.product-card {
  cursor: pointer;
  border-radius: 8px;
  overflow: hidden;
  background-color: #fff;
  border: 1px solid #eee;
  transition: box-shadow 0.3s;
}

.product-card:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.product-img {
  height: 200px;
  overflow: hidden;
  position: relative;
}

.product-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.product-card:hover .product-img img {
  transform: scale(1.05);
}

.sale-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #ff4d4f;
  color: white;
  padding: 3px 8px;
  font-size: 12px;
  border-radius: 4px;
}

.product-info {
  padding: 15px;
}

.product-title {
  margin: 0 0 10px;
  font-size: 16px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-price {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.current-price {
  font-size: 18px;
  color: #ff4d4f;
  font-weight: bold;
}

.original-price {
  margin-left: 10px;
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.product-sale {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
  align-items: center;
}

.price-tips {
  font-size: 14px;
  color: #409EFF;
  margin-right: auto;
  border: 1px solid #409EFF;
  padding: 2px 8px;
  border-radius: 12px;
  background-color: rgba(64, 158, 255, 0.1);
}

.stock-tips {
  font-size: 12px;
  color: #666;
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .banner-content {
    max-width: 80%;
    margin-left: 20px;
  }
  
  .product-list {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  }
  
  .feature-item {
    min-width: 150px;
  }
}
</style> 